package OnlineShopping;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HistoryRecord {
    private String userId; // 记录属于哪个用户
    private String historyFile = "E:\\Desktop\\大二上\\实训\\网上购物系统\\History.xlsx";

    public HistoryRecord() {
    }

    public HistoryRecord(String userId) {
        this.userId = userId;
    }
    // 添加购物记录
    public void addRecord(String record) {
        try (FileInputStream fis = new FileInputStream(historyFile);
             Workbook workbook = new XSSFWorkbook(fis)) {
            Sheet sheet = workbook.getSheetAt(0);
            int lastRow = sheet.getLastRowNum();
            Row newRow = sheet.createRow(lastRow + 1);

            newRow.createCell(0).setCellValue(userId); // 用户ID
            newRow.createCell(1).setCellValue(record); // 购物记录
            newRow.createCell(2).setCellValue(System.currentTimeMillis()); // 时间戳

            try (FileOutputStream fos = new FileOutputStream(historyFile)) {
                workbook.write(fos);
            }

            System.out.println("记录已添加: " + record);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 查询用户购物历史
    public void viewHistory(String userId) {
        try (FileInputStream fis = new FileInputStream(historyFile);
             Workbook workbook = new XSSFWorkbook(fis)) {
            Sheet sheet = workbook.getSheetAt(0);
            System.out.println("购物历史记录： ");
            System.out.println("正在查看历史记录，用户ID: " + userId);

            for (Row row : sheet) {
                Cell userIdCell = row.getCell(0); // 获取用户ID单元格
                if (userIdCell != null && userIdCell.getCellType() == CellType.STRING) {
                    String storedUserId = userIdCell.getStringCellValue();
                    System.out.println("存储的用户ID: " + storedUserId); // 打印存储的用户ID

                    if (storedUserId.equals(userId)) {
                        Cell recordCell = row.getCell(1);
                        Cell timestampCell = row.getCell(2);
                        String record = recordCell != null ? recordCell.getStringCellValue() : "无记录";
                        double timestamp = timestampCell != null ? timestampCell.getNumericCellValue() : 0.0;
                        System.out.println("记录： " + record + "， 时间： " + timestamp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
